<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <tree-table
        class="treetable"
        border
        show-index
        index-text="#"
        :selection-type="false"
        :expand-type="false"
        :data="cateList"
        :columns="columns"
      >
        <!-- 是否有效 -->
        <template slot-scope="scopes" slot="isok">
          <i
            v-if="scopes.row.cat_deleted === false"
            style="color:lightgreen;"
            class="el-icon-success"
          ></i>
          <i v-else class="el-icon-error" style="color:red;"></i>
        </template>
        <!-- 排序 -->
        <template slot-scope="scopes" slot="sort">
          <el-tag v-if="scopes.row.cat_level === 0" type="primary">标签一</el-tag>
          <el-tag v-else-if="scopes.row.cat_level === 1" type="warning">标签二</el-tag>
          <el-tag v-else type="danger">标签三</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="operation" slot-scope="scopeProps">
          <el-button
            type="primary"
            size="mini"
            @click="showEditCateDialog(scopeProps.row)"
            icon="el-icon-edit"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            @click="showDeleteDialog(scopeProps.row)"
            icon="el-icon-delete"
          >删除</el-button>
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      @close="addCateDialogClose"
      :visible.sync="addCateDialogVisible"
      width="50%"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称: " prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <!-- 父级分类 -->
        <el-form-item label="父级分类: ">
          <el-cascader
            clearable
            change-on-select
            expandTrigger="hover"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateListChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="添加分类"
      @close="editCateDialogClose"
      :visible.sync="editCateDialogVisible"
      width="50%"
    >
      <!-- 添加分类表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="编辑分类" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据列表
      cateList: [],
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      addCateDialogVisible: false,
      // 添加分类的表单数据对象
      addCateForm: {
        // 分类父 ID
        cat_pid: 0,
        // 分类名称
        cat_name: '',
        // 分类层级
        cat_level: 0
      },
      // 添加分类表单的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类列表
      parentCateList: [],
      // 选中的id
      selectedKeys: [],
      // 配置选项对象
      cascaderProps: {
        // 次级菜单的展开方式
        expandTrigger: 'hover',
        // 指定选项的值为选项对象的某个属性值
        value: 'cat_id',
        // 指定选项标签为选项对象的某个属性值
        label: 'cat_name',
        // 指定选项的子选项为选项对象的某个属性值
        children: 'children'
      },
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 表示，将当前列定义为模板列
          type: 'template',
          // 表示当前这一列使用的模板名称
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ],
      editCateDialogVisible: false,
      editForm: {},
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.cateList = res.data.result
      this.total = res.data.total
      // console.log(this.cateList)
    },
    // 监听pagesize改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 监听pagenum改变
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    showAddCateDialog() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) { return this.$message.error('获取父级分类列表失败') }
      // console.log(res.data)
      this.parentCateList = res.data
    },
    // 级联选择框中的内容发生变化时出发
    parentCateListChange() {
      // console.log(this.selectedKeys)
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        this.addCateForm.cat_level = this.selectedKeys.length
        // eslint-disable-next-line no-useless-return
        return
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击确定按钮，添加新分类
    addCate() {
      // console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 监听添加分类对话框关闭清空表单
    addCateDialogClose() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 显示编辑分类对话框
    showEditCateDialog(props) {
      this.editCateDialogVisible = true
      console.log(props)
      this.editForm = props
      // const { data: res } = await this.$http.put(`categories/${props.cat_id}`, { cat_name: '大家电' })
      // console.log(res)
    },
    // 监听编辑对话框关闭清空表单
    editCateDialogClose() {},
    // 点击确定按钮，发送编辑请求
    async eidtCate() {
      const {
        data: res
      } = await this.$http.put(`categories/${this.editForm.cat_id}`, {
        cat_name: this.editForm.cat_name
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.editCateDialogVisible = false
    },
    showDeleteDialog(props) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async (res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          console.log(props)
          const { data: result } = await this.$http.delete(`categories/${props.cat_id}`)
          if (result.meta.status !== 200) return this.$message.error('删除分类失败')
          this.getCateList()
        })
        .catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          console.log(err)
        })
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="less">
.treetable {
  margin-top: 15px;
}
.el-cascader-panel {
  height: 300px;
  box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.el-cascader-menu__wrap  {
  height: 100%;
}
.el-cascader-panel {
  background-color: #fff;
}
.el-cascader {
  width: 100%;
}
</style>
